import { DatePicker, Input, InputNumber, Select, Switch } from 'antd';
import { ActionConfigType } from './interfaces';
import { getMessage } from '@inbiz/react';
import operationFlagTitle from './operationFlagTitle';
import { getPlatform } from '@inbiz/utils';

export const EventsMap = {
  onload: 'onload',
  onSuccess: 'onSuccess',
  onError: 'onError',
  onDelete: 'onDelete',
  onAdd: 'onAdd',
  onEdit: 'onEdit',
  onOpen: 'onOpen',
  onClose: 'onClose',
  onQueryClick: 'onQueryClick',
  onClearClick: 'onClearClick',
  onQueryBoxChange: 'onQueryBoxChange',
  onExportParamFormat: 'onExportParamFormat',
  onOperateColumnFormat: 'onOperateColumnFormat',
  onParamFormat: 'onParamFormat',
  onColumnsFormat: 'onColumnsFormat',
  onClick: 'onClick',
  //antd
  onDblClickRow: 'onDblClickRow',
  onSelect: 'onSelect',
  onSelectAll: 'onSelectAll',
  onSelectInvert: 'onSelectInvert',
  onSelectNone: 'onSelectNone',
};
export enum OperatorEnum {
  eq = 'eq',
  neq = 'neq',
  gt = 'gt',
  gte = 'gte',
  lt = 'lt',
  lte = 'lte',
  like = 'like',
  nlike = 'nlike',
  nstartwith = 'nstartwith',
  startwith = 'startwith',
  endwith = 'endwith',
  nendwith = 'nendwith',
}

export enum ActionEnum {
  add = 'add',
  cancel = 'cancel',
  custom = 'custom',
  customColumn = 'customColumn',
  del = 'del',
  downloadTmpl = 'downloadTmpl',
  edit = 'edit',
  export = 'export',
  import = 'import',
  like = 'like',
  next = 'next',
  pre = 'pre',
  print = 'print',
  save = 'save',
  saveAndNew = 'saveAndNew',
  view = 'view',
}

export enum ConnectorEnum {
  and = 'and',
  or = 'or',
}

export enum UnitEnum {
  percentage = '%',
  pixel = 'px',
}

export enum InputTypeEnum {
  Text = 1,
  Number = 3,
  Date = 4,
  Select = 5,
  Switch = 6,
}

export var cardTmplModules = {
  antd: require('antd'),
  '@ant-design/icons': require('@ant-design/icons'),
  react: require('react'),
};

export const TmplPlaceConfigKey = {
  title: 'title',
  // img: 'img',
  dataItems: 'dataItems',
};

export const ActionPosition = {
  tableHeader: 'tableHeader',
  inline: 'inline',
};

export const SearchConst = {
  all: 'all',
  collapse: 'collapse',
  expanded: 'expanded',
  middle: 'middle',
  right: 'right',
};

export const InputTypeMap: { [key: number]: any } = {
  [InputTypeEnum.Text]: Input,
  [InputTypeEnum.Number]: InputNumber,
  [InputTypeEnum.Date]: DatePicker,
  [InputTypeEnum.Select]: Select,
  [InputTypeEnum.Switch]: Switch,
};

export const InlineDefaultActions = ['view', 'edit'];

export const TablePrefixCls = 'inbiz';

export const Actions = () => [
  {
    label: 'SubTable.button.add',
    value: 'add',
  },
  {
    label: 'SubTable.button.view',
    value: 'view',
  },
  {
    label: 'SubTable.button.edit',
    value: 'edit',
  },
  {
    label: 'SubTable.button.del',
    value: 'del',
  },
  {
    label: 'SubTable.button.custom',
    value: 'custom',
  },
];

export const ResConst = {
  other: 'other',
  success: 'success',
  error: 'error',
};
export const Option = () => ({
  actions: Actions(),
  auth: [
    {
      label: 'add',
      value: 'add',
    },
    {
      label: 'edit',
      value: 'edit',
    },
    {
      label: 'delete',
      value: 'del',
    },
  ],
  paramField: [{ label: 'ID', value: 'id' }],
  position: [
    { label: getMessage('SubTable.position.tableHeader'), value: 'tableHeader' },
    { label: getMessage('SubTable.position.inline'), value: 'inline' },
  ],
  openMode: [
    { label: getMessage('SubTable.openMode.modal'), value: 'modal' },
    { label: getMessage('SubTable.openMode.inline'), value: 'inline' },
    // { label: '新页面', value: 'page' },
    // { label: '抽屉-上', value: 'top' },
    // { label: '抽屉-下', value: 'bottom' },
    // { label: '抽屉-左', value: 'left' },
    // { label: '抽屉-右', value: 'right' },
  ],
  yesOrNo: [
    { value: '1', label: getMessage('SubTable.yesOrNo.yes') },
    { value: '0', label: getMessage('SubTable.yesOrNo.no') },
  ],
  fixed: [
    { value: 'left', label: getMessage('SubTable.fixed.left') },
    { value: 'right', label: getMessage('SubTable.fixed.right') },
    { value: 'none', label: getMessage('SubTable.yesOrNo.no') },
  ],
  sorter: [
    { value: 'on', label: getMessage('SubTable.sorter.on') },
    { value: 'off', label: getMessage('SubTable.sorter.off') },
  ],
  toolbarDisplayPosition: [
    { value: 'left', label: getMessage('SubTable.fixed.left') },
    { value: 'right', label: getMessage('SubTable.fixed.right') },
  ],
  toolbarDisplayQty: [
    { value: 1, label: getMessage('SubTable.toolbarDisplayQty.one') },
    { value: 2, label: getMessage('SubTable.toolbarDisplayQty.two') },
    { value: 3, label: getMessage('SubTable.toolbarDisplayQty.three') },
    { value: 4, label: getMessage('SubTable.toolbarDisplayQty.four') },
    { value: 5, label: getMessage('SubTable.toolbarDisplayQty.five') },
    { value: 6, label: getMessage('SubTable.toolbarDisplayQty.six') },
    { value: 7, label: getMessage('SubTable.toolbarDisplayQty.seven') },
    { value: 8, label: getMessage('SubTable.toolbarDisplayQty.eight') },
  ],
  actionDisplaySetup: [
    { value: 'text', label: getMessage('SubTable.display.text') },
    { value: 'icon', label: getMessage('SubTable.display.icon') },
    { value: 'iconText', label: getMessage('SubTable.display.iconText') },
  ],
  size: [
    { value: 30, label: 30 },
    { value: 60, label: 60 },
    { value: 90, label: 90 },
  ],
  suffixOfUnit: [
    { value: '%', label: '%' },
    { value: 'px', label: 'px' },
  ],
  pageSize: [
    { value: 10, label: '10/页' },
    { value: 20, label: '20/页' },
    { value: 30, label: '30/页' },
    { value: 50, label: '50/页' },
    { value: 100, label: '100/页' },
  ],
  unitOfWidth: [
    { value: 'px', label: getMessage('SubTable.unitOfWidth.px') },
    { value: '%', label: getMessage('SubTable.unitOfWidth.percent') },
  ],
  parentAction: [
    { value: 'add', label: 'SubTable.parentAction.add' },
    { value: 'view', label: 'SubTable.parentAction.view' },
    { value: 'edit', label: 'SubTable.parentAction.edit' },
  ],
  actionType: [
    { value: 'save', label: 'SubTable.actionType.save' },
    { value: 'saveAndNew', label: 'SubTable.actionType.saveAndNew' },
    { value: 'pre', label: 'SubTable.actionType.pre' },
    { value: 'next', label: 'SubTable.actionType.next' },
    { value: 'cancel', label: 'SubTable.actionType.cancel' },
    { value: 'custom', label: 'SubTable.actionType.custom' },
  ],
});

export const ActionTypeObj = Option().actionType.reduce((obj, type) => {
  obj[type.value] = type;
  return obj;
}, {});

export const ColumnConst = {
  index: 'inBizTableIndex',
  actions: 'inBizTableActions',
  subTableIndex: 'inBizSubTableIndex',
  subTableActions: 'inBizSubTableActions',
};
export const arrIsEmpty = (arr: any): boolean => {
  return !arr || !Array.isArray(arr) || arr.length === 0;
};
export const arrIsNotEmpty = (arr: ActionConfigType[] | undefined) => {
  return !arrIsEmpty(arr);
};
export const objIsEmpty = (obj: {}) => {
  return !obj || typeof obj !== 'object' || Object.keys(obj).length === 0;
};
export const objIsNotEmpty = (obj: {}) => {
  return !objIsEmpty(obj);
};

const setSelectProps = (options?: { label: string; value: string }[]) => {
  return {
    type: 'Select',
    options: options?.map((ele) => ({ ...ele, label: getMessage(ele.label) })),
    allowClear: true,
  };
};
const ActionsInHeader = [
  ActionEnum.add,
  ActionEnum.import,
  ActionEnum.export,
  ActionEnum.customColumn,
  ActionEnum.print,
];
const ActionsInInline = [ActionEnum.edit, ActionEnum.view, ActionEnum.del];
export const actionHeader = (authOption, isInline, fields) => [
  {
    title: getMessage('SubTable.column.actionType'),
    dataIndex: 'actionType',
    editData: {
      beforEdit: (record: any) => {
        if (ActionsInInline.includes(record?.actionType)) {
          record.position = 'inline';
        }
        if (ActionsInHeader.includes(record?.actionType)) {
          record.position = 'tableHeader';
        }
        return true;
      },
      afterEdit: (value: any, record: any) => {
        record.actionName = Option().actions.find((option) => option.value === value)?.label;
        return record;
      },
      ...setSelectProps(Option().actions),
      rules: [
        {
          required: true,
          message: getMessage('SubTable.message.actionTypeRequired'),
        },
      ],
    },
  },
  {
    dataIndex: 'operationflag',
    title: operationFlagTitle(),
    isIdentical: true,
    width: 150,
    editData: {
      // beforEdit?: (record: any) => boolean | object;
      type: 'AutoComplete',
      // rules: [
      //   {
      //     required: true,
      //   },
      // ],
      options: authOption,
    },
  },
  {
    title: getMessage('SubTable.column.actionName'),
    dataIndex: 'actionName',
    width: 100,
    editData: {
      type: 'MultilingualInput',
      rules: [
        {
          required: true,
        },
      ],
    },
  },
  // {
  //   title: '权限值',
  //   dataIndex: 'auth',
  //   width: 100,
  //   editData: {
  //     ...setSelectProps(Option().auth),
  //   },
  // },
  {
    title: getMessage('SubTable.column.page'),
    dataIndex: 'page',
    width: 200,
    editData: {
      type: 'PageSelect',
    },
  },
  // {
  //   title: getMessage('SubTable.column.paramField'),
  //   dataIndex: 'field',
  //   width: 100,
  //   editData: {
  //     ...setSelectProps(fields),
  //     beforEdit: (record: any) => record.actionType == 'view' || record.actionType == 'edit',
  //   },
  // },
  {
    title: getMessage('SubTable.column.position'),
    dataIndex: 'position',
    width: 100,
    editData: {
      beforEdit: (record: any) => {
        if (ActionsInInline.includes(record?.actionType)) {
          return {
            options: Option().position.filter(({ value }) => value === 'inline'),
          };
        }
        if (ActionsInHeader.includes(record?.actionType)) {
          return {
            options: Option().position.filter(({ value }) => value === 'tableHeader'),
          };
        }
        return true;
      },
      ...setSelectProps(Option().position),
      allowClear: false,
    },
  },
  {
    title: getMessage('SubTable.column.icon'),
    dataIndex: 'icon',
    width: 150,
    editData: {
      type: 'IconPicker',
    },
  },
  {
    title: getMessage('SubTable.column.openMode'),
    dataIndex: 'openMode',
    width: 100,
    editData: {
      beforEdit: (record: any) => {
        if (record.actionType !== 'add' || !isInline) {
          return {
            options: Option().openMode.filter(({ value }) => value !== 'inline'),
          };
        }
        return true;
      },
      ...setSelectProps(Option().openMode),
    },
  },
  {
    title: getMessage('SubTable.column.windowName'),
    dataIndex: 'windowName',
    editData: {
      type: 'MultilingualInput',
    },
  },
];

export const getPropHeader = () => [
  {
    title: getMessage('SubTable.column.propName'),
    dataIndex: 'propName',
    editData: {
      ...setSelectProps(),
      rules: [
        {
          required: true,
          message: getMessage('SubTable.message.needPropName'),
        },
      ],
      showSearch: true,
      filterOption: (input, option) => {
          return (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
      }
    },
  },
  {
    title: getMessage('SubTable.column.columnName'),
    dataIndex: 'columnName',
    width: 100,
    editData: {
      type: 'MultilingualInput',
    },
  },
  {
    title: getMessage('SubTable.column.width'),
    dataIndex: 'width',
    width: 100,
    editData: {
      type: 'InputNumber',
    },
  },
  {
    title: getMessage('SubTable.column.visible'),
    dataIndex: 'visible',
    width: 100,
    editData: {
      ...setSelectProps(Option().yesOrNo),
      showSearch: false,
    },
  },
  {
    title: getMessage('SubTable.column.sorter'),
    dataIndex: 'sorter',
    width: 100,
    editData: {
      ...setSelectProps(Option().sorter),
    },
  },
  {
    title: getMessage('SubTable.column.fixed'),
    dataIndex: 'fixed',
    editData: {
      ...setSelectProps(Option().fixed),
      allowClear: false,
    },
  },
];

export const ConfigHeader = () => [
  // {
  //   title: '显示位置',
  //   dataIndex: 'placeText',
  // },
  {
    title: getMessage('SubTable.column.label'),
    dataIndex: 'label',
    editData: {
      type: 'Input',
    },
  },
  {
    title: getMessage('SubTable.column.propName'),
    dataIndex: 'propName',
    editData: {
      ...setSelectProps(),
      showSearch: true,
      filterOption: (input, option) => {
        return (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
    }
    },
  },
];

export const ActionTypeMap = {
  add: [ActionEnum.save, ActionEnum.saveAndNew, ActionEnum.cancel, ActionEnum.custom],
  edit: [
    ActionEnum.save,
    ActionEnum.saveAndNew,
    ActionEnum.pre,
    ActionEnum.next,
    ActionEnum.cancel,
    ActionEnum.custom,
  ],
  view: [ActionEnum.pre, ActionEnum.next, ActionEnum.cancel, ActionEnum.custom],
};

export const SubWindowHeader = () => [
  {
    title: getMessage('SubTable.column.parentAction'),
    dataIndex: 'parentAction',
    width: 200,
    editData: {
      afterEdit: (value: any, record: any) => {
        const typeOptions = Option().actionType.filter(({ value: parentActionValue }) =>
          ActionTypeMap[value]?.includes(parentActionValue),
        );
        if (!typeOptions.find((option) => option.value === record.actionType)) {
          record.actionType = undefined;
          record.actionName = undefined;
        }
        return record;
      },
      ...setSelectProps(Option().parentAction),
      rules: [
        {
          required: true,
          message: getMessage('SubTable.message.parentActionRequired'),
        },
      ],
    },
  },
  {
    title: getMessage('SubTable.column.actionType'),
    dataIndex: 'actionType',
    width: 200,
    // render: (value: any, record: any) => {
    //   return Option().actionType.find((option) => option.value === record.actionType)?.label;
    // },
    editData: {
      afterEdit: (value: any, record: any) => {
        record.actionName = Option().actionType.find((option) => option.value === value)?.label;
        return record;
      },
      beforEdit: (record: any) => {
        return {
          options: Option()
            .actionType.map((ele) => ({ ...ele, label: getMessage(ele.label) }))
            .filter(({ value }) => ActionTypeMap[record?.parentAction]?.includes(value)),
        };
      },
      ...setSelectProps(Option().actionType),
      rules: [
        {
          required: true,
        },
      ],
    },
  },
  {
    title: getMessage('SubTable.column.actionName'),
    dataIndex: 'actionName',
    width: 100,
    editData: {
      type: 'MultilingualInput',
    },
  },
];

export const TabsConfig = (isInline) => ({
  actions: {
    table: {
      name: getMessage('SubTable.column.action'),
      formItems:
        getPlatform() == 'web'
          ? [
            // {
            //   name: 'toolbarDisplayPosition',
            //   label: '操作按钮显示位置',
            //   inputType: InputTypeEnum.Select,
            //   defaultValue: 'left',
            //   options: Option().toolbarDisplayPosition,
            // },
            {
              name: 'toolbarDisplayQty',
              label: getMessage('SubTable.form.toolbarDisplayQty'),
              inputType: InputTypeEnum.Select,
              defaultValue: 3,
              options: Option().toolbarDisplayQty,
            },
            {
              name: 'actionColumnWidth',
              label: getMessage('SubTable.form.actionColumnWidth'),
              inputType: InputTypeEnum.Number,
            },
            {
              name: 'tableHeaderBtnShow',
                label: getMessage('SubTable.form.subHeaderBtnDisplay'),
                inputType: InputTypeEnum.Select,
                defaultValue: 'text',
                options: Option().actionDisplaySetup,
            },
            {
              name: 'inLineBtnShow',
              label: getMessage('SubTable.form.subInLineBtnDisplay'),
              inputType: InputTypeEnum.Select,
              defaultValue: 'text',
              options: Option().actionDisplaySetup,
            },
            {
              name: 'fixedActionColumn',
              label: getMessage('SubTable.form.fixedActionColumn'),
              inputType: InputTypeEnum.Select,
              options: Option().fixed,
            },
          ]
          : [],
      // 表头
      header: (authOption) =>
        actionHeader(authOption, isInline).filter((col) => col.dataIndex !== 'auth'),
    },
  },
  attrs: {
    table: {
      name: getMessage('SubTable.attr'),
      formItems: [
        // {
        //   name: 'pageSize',
        //   label: '页记录数',
        //   inputType: InputTypeEnum.Select,
        //   defaultValue: 30,
        //   options: Option().pageSize,
        // },
        {
          name: 'widthUnit',
          label: getMessage('SubTable.column.widthUnit'),
          inputType: InputTypeEnum.Select,
          options: Option().unitOfWidth,
        },
      ],
      header: getPropHeader(),
    },
  },
  subWindow: {
    table:
      getPlatform() == 'web'
        ? {
          name: getMessage('SubTable.subWindow.name'),
          formItems: [
            {
              name: 'width',
              label: getMessage('SubTable.subWindow.width'),
              changeType: (value: string) => {
                return value === 'px' ? InputTypeEnum.Number : InputTypeEnum.Select;
              },
              initInputType: (values: { width: { widthSuffix: string } }) => {
                return values?.width?.widthSuffix === 'px'
                  ? InputTypeEnum.Number
                  : InputTypeEnum.Select;
              },
              children: [
                {
                  name: 'widowWidth',
                  inputType: InputTypeEnum.Select,
                  defaultValue: 30,
                  options: Option().size,
                  needChangeType: true,
                  proportion: '67%',
                },
                {
                  name: 'widthSuffix',
                  inputType: InputTypeEnum.Select,
                  defaultValue: UnitEnum.percentage,
                  options: Option().suffixOfUnit,
                  proportion: '33%',
                },
              ],
            },
            {
              name: 'height',
              label: getMessage('SubTable.subWindow.height'),
              changeType: (value: string) => {
                return value === 'px' ? InputTypeEnum.Number : InputTypeEnum.Select;
              },
              initInputType: (values: { height: { heightSuffix: string } }) => {
                return values?.height?.heightSuffix === 'px'
                  ? InputTypeEnum.Number
                  : InputTypeEnum.Select;
              },
              children: [
                {
                  name: 'windowHeight',
                  inputType: InputTypeEnum.Select,
                  defaultValue: 30,
                  options: Option().size,
                  needChangeType: true,
                  proportion: '67%',
                },
                {
                  name: 'heightSuffix',
                  inputType: InputTypeEnum.Select,
                  options: Option().suffixOfUnit,
                  proportion: '33%',
                },
              ],
            },
          ],
          header: SubWindowHeader(),
        }
        : {},
  },
});
